package com.rickpan.util;

import org.springframework.stereotype.Component;

import java.security.SecureRandom;
import java.util.Random;

/**
 * 分享码生成器
 * 
 * @author RickPan Team
 * @since 2025-01-05
 */
@Component
public class ShareCodeGenerator {

    private static final String CHARACTERS = "ABCDEFGHJKMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789";
    private static final int CODE_LENGTH = 12;
    private static final Random RANDOM = new SecureRandom();

    /**
     * 生成安全的分享码
     * 
     * 特点：
     * 1. 使用SecureRandom确保随机性
     * 2. 排除容易混淆的字符 (0, O, 1, I, l)
     * 3. 12位长度，提供足够的组合数量
     * 4. 大小写混合，增加复杂度
     * 
     * @return 12位分享码
     */
    public String generateShareCode() {
        StringBuilder code = new StringBuilder(CODE_LENGTH);
        
        for (int i = 0; i < CODE_LENGTH; i++) {
            int index = RANDOM.nextInt(CHARACTERS.length());
            code.append(CHARACTERS.charAt(index));
        }
        
        return code.toString();
    }

    /**
     * 生成指定长度的分享码
     * 
     * @param length 分享码长度
     * @return 指定长度的分享码
     */
    public String generateShareCode(int length) {
        if (length < 6 || length > 32) {
            throw new IllegalArgumentException("分享码长度必须在6-32位之间");
        }
        
        StringBuilder code = new StringBuilder(length);
        
        for (int i = 0; i < length; i++) {
            int index = RANDOM.nextInt(CHARACTERS.length());
            code.append(CHARACTERS.charAt(index));
        }
        
        return code.toString();
    }

    /**
     * 验证分享码格式
     * 
     * @param shareCode 分享码
     * @return 是否有效
     */
    public boolean isValidShareCode(String shareCode) {
        if (shareCode == null || shareCode.length() < 6 || shareCode.length() > 32) {
            return false;
        }
        
        // 检查是否只包含允许的字符
        for (char c : shareCode.toCharArray()) {
            if (CHARACTERS.indexOf(c) == -1) {
                return false;
            }
        }
        
        return true;
    }

    /**
     * 计算分享码的理论组合数量
     * 
     * @param length 分享码长度
     * @return 组合数量
     */
    public long calculateCombinations(int length) {
        return (long) Math.pow(CHARACTERS.length(), length);
    }
}
